package com.test;

import java.util.LinkedList;
import java.util.Scanner;

public class Exp2A {
	
	private LinkedList<String> list = new LinkedList<String>();
	private boolean isFinished = false;
	
	public static void main(String[] args) {
		Exp2A exp2a = new Exp2A();
		//创建并启动读取数据的线程（生产者线程）
		exp2a.new ReadThread().start();
		//创建并启动分析数据的线程（消费者线程）
		exp2a.new AnalysisThread().start();
	}
	
	class ReadThread extends Thread{
		public void run() {
			String line = null;
			try(Scanner cin = new Scanner(
					Exp2A.class.getClassLoader().getResourceAsStream("fdsdata20181025(0623-0624).txt"))){
				while(cin.hasNext()) {
					synchronized (list) {
						line = cin.nextLine();
						System.out.println("读取：" + line);
						list.add(line);
						//通知所有的线程
						list.notifyAll();
					}
				}
				synchronized (list) {
					isFinished = true;
					list.notifyAll();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	class AnalysisThread extends Thread{
		public void run() {
			String line = null;
			while(true) {
				synchronized (list) {
					while (list.isEmpty()) {
						if (isFinished) {
							return;
						} else {
							try {
								list.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					} //end while
					line = list.removeFirst();
				}// end synchronized
				System.out.println("分析： " + line);
			}
		} //end run
	}
}